#include "centriesmodel.h"
#include "constants.h"

CEntriesModel::CEntriesModel(CDatabase &db, QObject *parent):
        QAbstractTableModel(parent), m_db(db), m_showHide(false)
{
    this->setSupportedDragActions(Qt::MoveAction);
}

CEntriesModel::~CEntriesModel()
{
    qDeleteAll(m_list);
}

QVariant CEntriesModel::data(const QModelIndex &index, int role) const
{
    if(!index.isValid())
        return QVariant();

    CEntry *e = m_list.at(index.row());

    switch(role)
    {
        case Qt::DisplayRole: return e->getData(index.column(), m_showHide);
        case Qt::DecorationRole: return e->getDecoration(index.column());
        default: return QVariant();
    }
}

int CEntriesModel::rowCount(const QModelIndex&) const
{
    return m_list.count();
}

int CEntriesModel::columnCount(const QModelIndex&) const
{
    if(m_list.count())
        return CEntry::columnCount();

    return 0;
}

Qt::ItemFlags CEntriesModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags defaultFlags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;

    if (index.isValid())
        return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags;
    else
        return Qt::ItemIsDropEnabled | defaultFlags;
}

QVariant CEntriesModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(m_list.count()==0 || orientation!=Qt::Horizontal || role!=Qt::DisplayRole)
        return QVariant();

    return CEntry::getFieldName(section);
}

void CEntriesModel::setId(QString id)
{
    m_id = id;
    refill();
}

void CEntriesModel::refill()
{
    QList<CEntry*> tmp = m_list;
    m_list.clear();

    QList<QString> entries = m_db.getEntriesList(m_id);

    foreach(QString i, entries)
    {
        CEntry *e = new CEntry(m_db, i);
        m_list.append(e);
    }

    qDeleteAll(tmp);

    reset();
}

CEntry* CEntriesModel::getEntry(const QModelIndex &index) const
{
    if(!index.isValid())
        return 0;

    int row = index.row();
    return m_list.at(row);
}

CEntry* CEntriesModel::findEntry(QString id)
{
    foreach(CEntry* e, m_list)
    {
        if(e->id()==id)
            return e;
    }

    if(m_list.count())
        return m_list.at(0);

    return 0;
}

int CEntriesModel::findRowNumber(QString id)
{
    for(int i=0; i<m_list.count(); i++)
    {
        if(m_list.at(i)->id()==id)
            return i;
    }

    if(m_list.count())
        return 0;

    return -1;
}

QMimeData* CEntriesModel::mimeData(const QModelIndexList &indexes) const
{
    debug("Indexes count: " + QString::number(indexes.count()));
    debug("mimeData()");

    CEntry *entry = getEntry(indexes.at(0));
    if(entry==0)
        return new QMimeData();

    QMimeData *mimeData = new QMimeData();
    QByteArray encodedData;
    QDataStream in(&encodedData, QIODevice::WriteOnly);

    in << entry->id();

    mimeData->setData(MIME_ENTRY, encodedData);

    return mimeData;

}
